<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户名验证</title>
  <style>
    .green {
      color: green;
    }

    .red {
      color: red;
    }
  </style>
</head>

<body>
  <input type="text" placeholder="请输入用户名"><span></span>
  <script>
    var input = document.querySelector('input')
    var span = document.querySelector('span')
    var reg = /^[0-9a-zA-Z_-]{4,12}$/
    input.onblur = function () {
      var val = input.value;
      if (reg.test(val)) {
        span.innerHTML = '用户名正确'
        span.className = 'green'
      } else {
        span.innerHTML = '用户名必须4-12位且不能包含特殊符号'
        span.className = 'red'
      }
    }
  </script>
</body>

</html>